﻿using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DMS.Common.Extensions;
using DMS.Common.Model.Result;
using DMS.Redis;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar.Template.Extensions;
using SqlSugar.Template.IService;
using SqlSugar.Template.IService.Param;
using SqlSugar.Template.IService.Result;
using SqlSugar.Template.Models;

namespace BookApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]

    public class BookController : ControllerBase
    {

        private readonly IBookService bookService;
      
   

        private readonly IStockLstService stockLstService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bookService"></param>
        /// <param name="stockLstService"></param>
        /// <param name="userAuth"></param>
        /// <param name="redisRepository"></param>
        public BookController(IBookService bookService, IStockLstService stockLstService)
        {
            this.bookService = bookService;       
         
            this.stockLstService = stockLstService;
        }

        /// <summary>
        /// 事物添加处理
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("AddTran")]
        [Authorize]
        public async Task<ResponseResult> AddTranAsync(AddBookParam param)
        {
          
            var result = await bookService.AddTran(param);      
            return result;
        }

        /// <summary>
        /// 雪花ID
        /// </summary>
        /// <returns></returns>
        
        [HttpGet("GetId")]
        [Authorize]
        public  ResponseResult GetIdAsync( )
        {
            ResponseResult result = new();
            var idGenerator = new SnowflakeIdGenerator(1, 1);
            //Random random = new Random();
            //int randomNumber = random.Next(1000, 10000);
            //var id = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + randomNumber;
            result.data = idGenerator.NextId();
            //result.data = id;                 
            return result;
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id">自增主键</param>
        /// <returns></returns>
        [HttpPost("Delete")]
        [Authorize]
       
        public async Task<ResponseResult> DeleteAsync(long Id)
        {
            var result = await bookService.DeleteAsync(Id);
            if (Convert.ToInt32(result.data) > 0)
            {
                var stock = await bookService.GetBookAsync(Id);
                if (stock!=null||stock.data.StockId>0)
                {
                await stockLstService.DeleteAsync(stock.data.StockId);
                }
            }
               
            return result;
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        [HttpPost("Update")]
        [Authorize]
        public async Task<ResponseResult> UpdateAsync(EditBookParam book)
        {
            var result = await bookService.UpdateAsync(book);          
            return result;
        }

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>

        [HttpGet("SearchBook")]
        [Authorize]
        public async Task<ResponseResult<PageModel<BookResult>>> SearchBookAsync([FromQuery] SearchBookParam param)
        {
            ResponseResult<PageModel<BookResult>> result = new()
            {
                data = new PageModel<BookResult>()
            };
            //按时间来查询
            if (string.IsNullOrWhiteSpace(param.StockCode) && string.IsNullOrWhiteSpace(param.StockCode))
            {
                result = await bookService.SearchBookAsync(param);
                for (int i = 0; i < result.data.resultList.Count; i++)
                {
                    var stockN = await stockLstService.GetStockAsync(result.data.resultList[i].StockId);
                    if (stockN != null && stockN.data.Count > 0)
                    {
                        result.data.resultList[i].stockLsts.AddRange(stockN.data);
                    }
                }
            }//按条件
            else
            {
                var res = await stockLstService.GetLstStockByStockCodeAndClosingCodeAsync(param.StockCode, param.ClosingCode);
                for (int i = 0; i < res.data.Count; i++)
                {
                    var mode = await bookService.GetBookAsync(res.data[i].BookId);
                    if (mode.data.UserId==param.UserId)
                    {
                        if (mode.data.StockId == res.data[i].BookId)
                        {
                            result.data.resultList.Add(mode.data);
                        }
                    }   
                }
                for (int j = 0; j < result.data.resultList.Count; j++)
                {
                    var book = res.data.Where(op => op.BookId == result.data.resultList[j].StockId).First();
                    if (book != null)
                    {
                        result.data.resultList[j].stockLsts.Add(book);
                    }
                }
                if (result.data == null)
                {
                    result.errno = 1;
                    result.errmsg = "未找到相关数据";
                    return result;
                }

                if (result.data.pageIndex < 1)
                {
                    result.errno = 1;
                    result.errmsg = "未找到相关数据";
                    return result;
                }

                if (result.data.pageSize < 1)
                {
                    result.errno = 1;
                    result.errmsg = "未找到相关数据";
                    return result;
                }

                int totalItems = result.data.totalRecord;
                int totalPages = (int)Math.Ceiling(totalItems / (double)result.data.pageSize);

                // 确保请求的页码在有效范围内
                if (result.data.pageIndex > totalPages)
                {
                    result.data.pageIndex = totalPages;
                }

                // 计算当前页的开始索引和结束索引
                int startIndex = (result.data.pageIndex - 1) * result.data.pageSize;
                int endIndex = Math.Min(startIndex + result.data.pageSize, totalItems);

                // 返回当前页的元素
                result.data.resultList.GetRange(startIndex, endIndex - startIndex);
            }
            return result;
        }

    }
}
